import dataStorage from './dataStorage.js'
import checkPlat from './checkPlat.js'
import {
	Watch
} from './watch.js'

// 配置集
import platConfig from './platConfig.js'

var common = {};
// 外部引入方法添加到common对象中
if (!common.externalInstalled) {
	common.externalInstalled = true
	Object.defineProperties(common, {
		$dataStorage: {
			value: dataStorage
		},
		$checkPlat: {
			value: checkPlat
		},
		$platConfig: {
			value: platConfig
		}
	})
}

var app = getAppObject();
var firstOpen = true;
var callbackObj = null;

function getAppObject() {
	app = getApp()
	if (!app) {
		setTimeout(function() {
			getAppObject()
		}, 300)
	} else {
		return app
	}
}

// 首页路径
var firstPage = common.$platConfig.firstPage
var wxapp_type = common.$platConfig.wxapp_type

// #ifdef H5
common.jweixin = require('./jweixin-1.4.0.js');
 
var requestDomain = '/';
if (process.env.NODE_ENV === 'development') {
	console.log('开发环境')

	//判断是不是 localhost:8080打开的
	if (location.host == 'localhost:8080') {
		// location.href = location.href.replace('localhost:8080', 'www.group.com');
	}
	if (location.host == '127.0.0.1:8080') {
		// location.href = location.href.replace('127.0.0.1:8080', 'www.group.com');
	}
	
	if(common.$platConfig.h5_test_domain != ''){
		requestDomain = common.$platConfig.h5_test_domain
	}else{
		requestDomain = location.protocol + '//' + location.host + '/';
	}
} else {
	requestDomain = location.protocol + '//' + location.host + '/';
}
var device_id = uni.getStorageSync('device') ? uni.getStorageSync('device') : 'packapp';
var app_type = 'packapp';
// #endif

// #ifdef MP-WEIXIN || MP-ALIPAY
var requestDomain = common.$platConfig.mp_domain
// #endif

var requestUrl = requestDomain + 'appapi.php?c=';
var requestPluginUrl = requestDomain + 'plugin.php?plugin=vote&from=house&type=api&c=';
var requestPluginUrlCommon = requestDomain + 'plugin.php?plugin=';

var wxappVersionCode = 1510;
var tmpParam = {};

// #ifdef MP-WEIXIN
var device_id = 'wxapp';
var app_type = 'wxapp';
// #endif

// #ifdef MP-ALIPAY
var device_id = 'alipayapp';
var app_type = 'alipayapp';
// #endif

common.requestDomain = requestDomain;
common.wxapp_type = wxapp_type;
common.device_id = device_id;
common.app_type = app_type;
common.post = function(url, param, callFun, that, errFun) {
	 
	if (typeof(url) == 'undefined' || url == '') {
		return false;
	}
	var postUrl = requestUrl + url;
	if (param && param.plugin) {
		postUrl = requestPluginUrlCommon + url;
	}

	param = param ? param : {}
	param.now_lang = wx.getStorageSync('now_lang');
	param.wxapp_type = wxapp_type;
	param.app_type = common.app_type;
	param['Device-Id'] = common.device_id;
	param.ticket = uni.getStorageSync('ticket') ? uni.getStorageSync('ticket') : ''; 
	param.app_version = wxappVersionCode;

	var wxapp_config = wx.getStorageSync('wxapp_config');
	if (wxapp_config && wxapp_config.city) {
		param.now_city = wxapp_config.city.top_city ? wxapp_config.city.top_city.area_id : wxapp_config.city.area_id;
		if (wxapp_config.city.area_id && wxapp_config.city.top_city && wxapp_config.city.top_city.area_id != wxapp_config.city
			.area_id) {
			param.now_area = wxapp_config.city.area_id;
		}
	} else {
		var city_param = wx.getStorageSync('city_param')
		param.now_city = city_param && city_param.now_city ? city_param.now_city : ''
		param.now_area = city_param && city_param.now_area ? city_param.now_area : ''
	}
	
	
	// #ifdef H5
		// userAgent中的，一般用于APP的页面
		if(common.$checkPlat.checkApp()){
			var reg = /now_city=(.*?),/;
			var arr = reg.exec(navigator.userAgent);
			if(arr !== null){
				param.now_city = arr[1];
			}
		}
	// #endif

	var shop_city = app ? app.globalData.delivery_address : '';
	if (shop_city) {
		param.now_shop_city = shop_city.city_id;
	}
	// #ifdef H5
		// userAgent中的，一般用于APP的页面
		if(common.$checkPlat.checkApp()){
			var reg = /now_shop_city=(.*?),/;
			var arr = reg.exec(navigator.userAgent);
			if(arr !== null){
				param.now_shop_city = arr[1];
			}
		}
	// #endif
	
	
	delete param['that'];
	if (!param.noTip) {
		uni.showLoading()
	}
	console.log('请求路径 ', postUrl, '请求参数 ', param);
	uni.request({
		url: postUrl,
		data: param,
		header: {
			'Content-Type': 'application/json'
		},
		method: "POST",
		success: function(res) {
			console.log('请求结果', postUrl, res)
			if (res.data.errorCode == "0") {
				if (callFun) {
					if (!param.noTip) {
						uni.hideLoading();
					}
					if (typeof(callFun) == 'function') {
						callFun(res.data.result)
					} else {
						that[callFun](res.data.result);
					}
				}

			} else if (typeof(errFun) == 'function') {
				errFun(res)
			} else if (errFun && errFun != 'back') {
				that[errFun](res.data);
			} else {
				if (!param.noTip) {
					uni.hideLoading();
				}
				var contents = res.data.errorMsg;
				if (!contents) {
					// contents = common.changeTxt('请求错误')
					console.log('请求错误', postUrl)
					return
				}
				if (res.data.errorCode == "60000001") {
					contents += app ? common.changeTxt(',请点击右上角关闭小程序') : ',请点击右上角关闭小程序'
				} 
				wx.showModal({
					title: app ? common.changeTxt('提示') : '提示',
					content: contents,
					showCancel: false,
					success: function() {  
						if (errFun == 'back') {
							wx.navigateBack();
						} else if (res.data.errorCode == "60000001") {
							common.post(url, param, callFun, that, errFun)
						}
					}
				});
			}
		},
		fail: function(res) {
			console.log(postUrl);
			console.log(res);
			console.log("请求失败了啊");
			if (!param.noTip) {
				uni.hideLoading();
			}
			if (typeof(errFun) == 'function') {
				errFun(res)
			} else if (errFun && errFun != 'back') {
				that[errFun](res.data);
			}
			// if (res.errMsg.indexOf('No address associated with hostname') != -1) {
			//   return
			// }
			// wx.showModal({
			//   title: '提示',
			//   content: '网络错误，点击确认后重试！',
			//   success:function(res){
			//     if (res.confirm) {
			//       common.post(url, param, callFun, that, errFun)
			//     }
			//   }
			// })
			return {};
		},
		complete: function() {
			if (!param.noTip) {
				uni.hideLoading();
			}
		}
	});
};
common.plugin_post = function(url, param, callFun, that, errFun) {

	if (typeof(url) == 'undefined') {
		return false;
	}
	var postUrl = requestPluginUrl + url;
	param = param ? param : {}
	param.now_lang = wx.getStorageSync('now_lang');
	param.wxapp_type = wxapp_type;
	param.app_type = common.app_type;
	param['Device-Id'] = common.device_id;
	param.ticket = uni.getStorageSync('ticket') ? uni.getStorageSync('ticket') : ''; 
	param.app_version = wxappVersionCode;

	var wxapp_config = wx.getStorageSync('wxapp_config');
	if (wxapp_config && wxapp_config.city) {
		param.now_city = wxapp_config.city.top_city ? wxapp_config.city.top_city.area_id : wxapp_config.city.area_id;
		if (wxapp_config.city.area_id && wxapp_config.city.top_city && wxapp_config.city.top_city.area_id != wxapp_config.city
			.area_id) {
			param.now_area = wxapp_config.city.area_id;
		}
	} else {
		var city_param = wx.getStorageSync('city_param')
		param.now_city = city_param && city_param.now_city ? city_param.now_city : ''
		param.now_area = city_param && city_param.now_area ? city_param.now_area : ''
	}

	var shop_city = app ? app.globalData.delivery_address : '';
	if (shop_city) {
		param.now_shop_city = shop_city.city_id;
	}
	delete param['that'];
	if (!param.noTip) {
		uni.showLoading()
	}
	console.log('请求路径 ', postUrl, '请求参数 ', param);
	uni.request({
		url: postUrl,
		data: param,
		header: {
			'Content-Type': 'application/json'
		},
		method: "POST",
		success: function(res) {
			console.log('请求结果', postUrl, res)
			if (res.data.errorCode == "0") {
				if (callFun) {
					uni.hideToast();
					if (typeof(callFun) == 'function') {
						callFun(res.data.result)
					} else {
						that[callFun](res.data.result);
					}
				}

			} else if (typeof(errFun) == 'function') {
				errFun(res)
			} else if (errFun && errFun != 'back') {
				that[errFun](res.data);
			} else {
				uni.hideToast();
				var contents = res.data.errorMsg;
				if (!contents) {
					// contents = common.changeTxt('请求错误')
					console.log('请求错误', postUrl)
					return
				}
				if (res.data.errorCode == "60000001") {
					contents += ',' + common.changeTxt('请点击右上角关闭小程序')
				}
				wx.showModal({
					title: common.changeTxt('提示'),
					content: contents,
					showCancel: false,
					success: function() {
						if (errFun == 'back') {
							wx.navigateBack();
						} else if (res.data.errorCode == "60000001") {
							common.post(url, param, callFun, that, errFun)
						}
					}
				});


			}
		},
		fail: function(res) {
			console.log(postUrl);
			console.log(res);
			console.log("请求失败了啊");
			wx.hideLoading()
			if (typeof(errFun) == 'function') {
				errFun(res)
			} else if (errFun && errFun != 'back') {
				that[errFun](res.data);
			}
			// if (res.errMsg.indexOf('No address associated with hostname') != -1) {
			//   return
			// }
			// wx.showModal({
			//   title: '提示',
			//   content: '网络错误，点击确认后重试！',
			//   success:function(res){
			//     if (res.confirm) {
			//       common.post(url, param, callFun, that, errFun)
			//     }
			//   }
			// })
			return {};
		},
		complete: function() {
			uni.hideLoading()
		}
	});
};
common.upFormid = function(formid, successFunc) {
	if (typeof formid == 'object') {
		formid = formid.detail.formId;
	}
	console.log('formid', formid);
	if (!formid || formid == '' || formid == 'the formId is a mock one') {
		console.log('模拟请求 formId');
		if (successFunc) {
			successFunc();
		}
		return false;
	}
	var param = {};
	param.ticket = wx.getStorageSync('ticket');
	if (!param.ticket || param.ticket == '') {
		if (successFunc) {
			successFunc();
		}
		return false;
	}
	param['Device-Id'] = common.device_id;
	param.app_version = 500;
	param.formid = formid;

	var postUrl = requestUrl + 'Wxapp&a=post_formid';
	wx.request({
		url: postUrl,
		data: param,
		header: {
			'Content-Type': 'application/json'
		},
		method: "POST",
		complete: function() {
			if (successFunc) {
				successFunc();
			}
		}
	});
};
/* 经纬度转码至百度 */
common.changeLocation = function(callFun, that, lng, lat, ltype) {
	var data = {
		lng: lng,
		lat: lat,
		lbs_type: ltype,
		geocoder: true
	};
	wx.request({
		url: requestDomain + "index.php?c=Map&a=toBaidu",
		data: data,
		header: {
			'Content-Type': 'application/json'
		},
		method: "POST",
		success: function(res) {
			if (typeof callFun == 'function') {
				callFun(res.data)
			} else {
				console.log('that', that);
				that[callFun](res.data);
			}

		}
	});
}
/* ltype = baidu 转码为百度地图坐标，gps时直接返回*/
common.getLocation = function(callFun, that, ltype, lng, lat, geoType) {
	let str = geoType ? geoType : 'wgs84'
	uni.getLocation({
		type: str,
		success: function(res) {
			console.log('3333333333333000000', res)
			if (res.errMsg == "getLocation:ok") {
				if (ltype == 'baidu') {
					var data = {
						lng: res.longitude,
						lat: res.latitude,
						geocoder: true
					};
					if (lng && lat) {
						data.lng = lng;
						data.lat = lat;
						console.log("今天")
					}
					common.changeLocation(callFun, that, data.lng, data.lat, ltype)

				} else {
					if (typeof(callFun) == 'function') {
						callFun({
							lng: res.longitude,
							lat: res.latitude
						})
					} else {
						that[callFun]({
							lng: res.longitude,
							lat: res.latitude
						});
					}

				}
			}
		},
		fail: function(res) {
			console.log(res);
			if (typeof(callFun) == 'function') {
				callFun(res)
			} else {
				that[callFun](res);
			}
		}
	})
};

common.arrsort = function(arr) {
	var newArr = [];
	for (var i in arr) {
		newArr.push(arr[i]);
	}
	return newArr;
}
common.arrunique = function(arr) {
	var n = [];
	for (var i = 0; i < arr.length; i++) {
		if (n.indexOf(arr[i]) == -1) n.push(arr[i]);
	}
	return n;
}
common.callPhone = function(phone) {
	var phoneTmp = phone.split(' ');
	var phoneArr = [];
	for (var i in phoneTmp) {
		if (phoneTmp[i].length > 4) {
			phoneArr.push(phoneTmp[i]);
		}
	}
	//if(phoneArr.length > 1){
	wx.showActionSheet({
		itemList: phoneArr,
		success: function(res) {
			if (!res.cancel) {
				wx.makePhoneCall({
					phoneNumber: phoneArr[res.tapIndex]
				});
			}
		}
	});
	//}else{
	//    wx.makePhoneCall({phoneNumber:phoneArr[0]});
	//}
}

/*
 *  打开地图
 */
common.openMap = function(param) {
	if (!app) {
		app = getApp();
	}
	
	//谷歌地图模式下直接唤起地图
	if (app.globalData.config.config.map_config == 'google') {
		wx.openLocation({
			latitude: param.lng * 1,
			longitude: param.lat * 1,
			scale: 18,
			name: param.name,
			address: param.address
		});
	}else{
		tmpParam.name = param.name;
		tmpParam.address = param.address;
		if (param.type == 'baidu') {
			common.post('Map&a=baiduToGcj02', {
				baidu_lat: param.lat,
				baidu_lng: param.lng
			}, "getMap", this);
		} else {
			common.getMap({
				lat: param.lat,
				lng: param.lng
			});
		}
	}
}
common.getMap = function(result) {
	uni.hideToast();
	
	//#ifdef MP-WEIXIN || MP-ALIPAY
		uni.openLocation({
			latitude: parseFloat(result.lat),
			longitude: parseFloat(result.lng),
			name: tmpParam.name,
			address: tmpParam.address
		});
	//#endif
	
	//#ifdef H5
		if (common.$checkPlat.checkWeixin()) {
			common.jweixin.openLocation({
				latitude: parseFloat(result.lat),
				longitude: parseFloat(result.lng),
				name: tmpParam.name,
				address: tmpParam.address, 
				scale: 14,
				infoUrl: window.location.href
			});
		}else{
			uni.openLocation({
				latitude: parseFloat(result.lat),
				longitude: parseFloat(result.lng),
				name: tmpParam.name,
				scale: 14,
				address: tmpParam.address
			});
		}
	//#endif
}

common.isAliApp = false
common.parseUrl = function(url, root, isReturn, pageTitle) {
	uni.showLoading({
		mask: true
	});
	var tmpArr = [];
	var goType = '';
	var goParam = '';
	var goPath = '';
	//快店详情
	if (url.indexOf('c=Shop&a=index&shop-id') >= 0) {
		goType = 'page';
		goPath = '/pages/shop_new/shopDetail/shopDetail';
		
		goPath = goPath + '?store_id=' + common.getUrlParam(url, 'shop-id');
		if (common.getUrlParam(url, 'village_id')) {
			goPath  = goPath + '&village_id=' + common.getUrlParam(url, 'village_id');
		}
	} else if (url.indexOf('c=Shop&a=classic_shop&shop_id=') >= 0) {
		tmpArr = url.split('=');
		goType = 'shopDetail';
		goParam = tmpArr.pop();
		goPath = '/pages/shop_new/shopDetail/shopDetail';
	} else if (url.indexOf('c=Shop&a=status') >= 0) {
		goType = 'page';
		goPath = '/pages/shop_new/orderDetail/orderDetail?order_id=' + common.getUrlParam(url, 'order_id');
	} else if (url.indexOf('c=Merchant&a=shop') >= 0) {
		goType = 'page';
		goPath = '/pages/store/homePage?store_id=' + common.getUrlParam(url, 'store_id');
	} else if (url.indexOf('c=Shop&a=index#shop-') >= 0) {
		tmpArr = url.split('-');
		goType = 'shopDetail';
		goParam = tmpArr.pop();
		goPath = '/pages/shop_new/shopDetail/shopDetail';
	} else if (url.indexOf('c=Shop&a=index&#cat-') >= 0) {
		tmpArr = url.split('-');
		goType = 'shopCat';
		goParam = tmpArr.pop();
		goPath = '/pages/shop_new/cart/cart';
	}  else if (url.indexOf('c=Shop&a=index&cat=') >= 0) {
		tmpArr = url.split('=');
		goType = 'shopCat';
		goParam = tmpArr.pop();
		goPath = '/pages/shop_new/cart/cart';
	} else if (url.indexOf('c=Shop&a=classic_cat&cat_url=') >= 0) {
		tmpArr = url.split('=');
		goType = 'shopCat';
		goParam = tmpArr.pop();
		goPath = '/pages/shop_new/cart/cart';
	} else if (url.indexOf('c=Shop&a=classic_cat&cat=') >= 0) {
		tmpArr = url.split('=');
		goType = 'shopCat';
		goParam = tmpArr.pop();
		goPath = '/pages/shop_new/cart/cart';
	} else if (url.indexOf('c=Shop&a=index#good-') >= 0) {
		tmpArr = url.split('-');
		goType = 'shopGood';
		goParam = [];
		goParam.push(tmpArr.pop());
		goParam.push(tmpArr.pop());
		goPath = '/pages/shop_new/goodsDetail/goodsDetail';
	} else if (url.indexOf('c=Shop&a=classic_good') >= 0) {
		goType = 'shopGood';
		goParam = [];
		goParam.push(common.getUrlParam(url, 'good_id'));
		goParam.push(common.getUrlParam(url, 'shop_id'));
		goPath = '/pages/shop_new/goodsDetail/goodsDetail';
	} else if (url.indexOf('c=Shop&a=index') >= 0 || url.indexOf('pages/shop_index/index') != -1 || url.indexOf('c=Shop&a=classic_index') >= 0) {
		goType = 'shopIndex';
		goParam = '';
		goPath = '/pages/shop_index/index';
	} else if (url.indexOf('c=Merchant&a=shop') >= 0) {
		goType = 'page';
		goPath = '/pages/store/homePage?store_id=' + common.getUrlParam(url, 'store_id');
	} else if (url.indexOf('c=My&a=shop_order_list') >= 0) {
		goType = 'page';
		goPath = '/pages/my/my_order';
	} else if (url.indexOf('c=My&a=pay') >= 0 && url.indexOf('mer_id=') >= 0) {
		goType = 'storePrepay';
		goParam = common.getUrlParam(url, 'mer_id');
		goPath = '';
	} else if (url.indexOf('c=Home&a=index') >= 0 || url.indexOf('/pages/plat_menu/index') != -1) {
		goType = 'homeIndex';
		goPath = '/pages/plat_menu/index';
	} else if (url.indexOf('c=My&a=index') >= 0 || url.indexOf('/pages/plat_menu/my') != -1) {
		goType = 'myIndex';
		goPath = '/pages/plat_menu/my';
	} else if (url.indexOf('/pages/plat_menu/store') != -1) {
		goType = 'storeIndex';
		goPath = '/pages/plat_menu/store';
	} else if (url.indexOf('c=Pay&a=check') >= 0) {
		goType = 'Pay';
		goParam = {};
		goParam.order_id = common.getUrlParam(url, 'order_id');
		goParam.order_type = common.getUrlParam(url, 'type');
		goPath = '';
	} else if (url.indexOf('appoint_menu/index') >= 0) {
		goType = 'appointIndex';
		goPath = '/pages/appoint_menu/index';
	} else if (url.indexOf('village_menu/index') >= 0) {
		goType = 'villageIndex';
		goPath = '/pages/village_menu/index';
	} else if (url.indexOf('village_menu/convenient') >= 0) {
		goType = 'villageConvenient';
		goPath = '/pages/village_menu/convenient';
	} else if (url.indexOf('village_menu/resident') >= 0) {
		goType = 'villageResident';
		goPath = '/pages/village_menu/resident';
	} else if (url.indexOf('village_menu/my') >= 0) {
		goType = 'villageMyindex';
		goPath = '/pages/village_menu/my';
	} else if (url.indexOf('/packapp/plat_live') >= 0) {
		goType = 'page';
		goPath = url.split('/packapp/plat_live')[1];
	} else if (url.indexOf('/packapp/plat') >= 0) {
		goType = 'page';
		goPath = url.split('/packapp/plat')[1];
	}else if(url.indexOf('/packapp/village') >= 0){
		goType = 'page';
		goPath = url.split('/packapp/village')[1];
	}else if(url.indexOf('/packapp/plat_dev') >= 0){
		goType = 'page';
		goPath = url.split('/packapp/plat_dev')[1];
	} else if (url.indexOf('shop_new/confirmOrder/pay') >= 0) {
		goType = 'page';
		var tmpParam = url.split('?');
		goPath = '/pages/shop_new/confirmOrder/pay' + (tmpParam.length >= 2 ? '?' + tmpParam[1] : '');
	} else if (url.indexOf('pages/my/address') >= 0) {
		goType = 'page';
		goPath = '/pages/my/address';
	} else {
		goType = 'url';
		goParam = url;
		goPath = '';
	}
	if (isReturn == true) {
		wx.hideLoading()
		return {
			goType: goType,
			goParam: goParam,
			goPath: goPath
		};
	}


	console.log('=====goUrl======');
	console.log('old_url', url);
	console.log('goType', goType);
	console.log('goPath', goPath);
	console.log('goParam', goParam);

	if ((goType != 'url' && goType != 'page') && (url.indexOf('Shop') != -1 || url.indexOf('shop') != -1)) {
		common.gotoShopPage(goType, goParam, pageTitle)
	} else if (goType == 'homeIndex') {
		if (common.checkIsFooterPage("/pages/plat_menu/index")) {
			wx.switchTab({
				url: "/pages/plat_menu/index"
			});
		} else {
			wx.navigateTo({
				url: '/pages/nofooter/index',
			})
		}
	} else if (goType == 'storeIndex') {
		if (common.checkIsFooterPage("/pages/plat_menu/store")) {
			wx.switchTab({
				url: "/pages/plat_menu/store"
			});
		} else {
			wx.navigateTo({
				url: '/pages/nofooter/store/store_index',
			})
		}
	} else if (goType == 'myIndex') {
		if (common.checkIsFooterPage("/pages/plat_menu/my")) {
			wx.switchTab({
				url: "/pages/plat_menu/my"
			});
		} else {
			wx.navigateTo({
				url: '/pages/nofooter/my_index',
			})
		}
	} else if (goType == 'shopSpecial') {
		wx.navigateTo({
			url: "/pages/shop/special?id=" + goParam
		});
	} else if (goType == 'merchantCard') {
		wx.navigateTo({
			url: "/pages/merchant/card"
		});
	} else if (goType == 'merchantOrder') {
		wx.navigateTo({
			url: "/pages/merchant/order"
		});
	} else if (goType == 'merchantCoupon') {
		wx.navigateTo({
			url: "/pages/merchant/coupon"
		});
	} else if (goType == 'merchantRight') {
		wx.navigateTo({
			url: "/pages/merchant/right"
		});
	} else if (goType == 'merchantPersonal') {
		wx.navigateTo({
			url: "/pages/merchant/personal"
		});
	} else if (goType == 'merchantPoint') {
		wx.navigateTo({
			url: "/pages/merchant/point"
		});
	} else if (goType == 'merchantTransrecord') {
		wx.navigateTo({
			url: "/pages/merchant/transrecord"
		});
	} else if (goType == 'merchantPrepay') {
		wx.navigateTo({
			url: "/pages/merchant/prepay"
		});
	} else if (goType == 'merchantCouponList') {
		wx.navigateTo({
			url: "/pages/merchant/coupon_list"
		});
	} else if (goType == 'merchantStore') {
		wx.navigateTo({
			url: "/pages/merchant/store"
		});
	} else if (goType == 'merchantShopList') {
		wx.navigateTo({
			url: "/pages/merchant/store?goparam=shop"
		});
	} else if (goType == 'storeOrderList') {
		wx.navigateTo({
			url: "/pages/my/store_order?mer_id=" + goParam
		});
	} else if (goType == 'groupOrderList') {
		wx.navigateTo({
			url: "/pages/my/group_order?mer_id=" + goParam
		});
	} else if (goType == 'shopOrderList') {
		wx.navigateTo({
			url: "/pages/my/shop_order?mer_id=" + goParam
		});
	} else if (goType == 'shopProductDetail') {
		console.log(url);
		var goUrl = "/pages/shop/product?product_id=" + common.getUrlParam(url, 'product_id');
		var otherLink = common.getUrlParam(url, 'otherLink');
		if (otherLink != '') {
			goUrl += "&otherLink=" + otherLink;
		}
		console.log(goUrl);
		wx.navigateTo({
			url: goUrl
		});
	} else if (goType == 'storePrepay') {
		wx.navigateTo({
			url: "/pages/store/prepay?mer_id=" + goParam
		});
	} else if (goType == 'groupDetail') {
		wx.navigateTo({
			url: "/pages/group/detail?group_id=" + goParam
		});
	} else if (goType == 'Pay') {
		console.log('Pay', goType);
		wx.navigateTo({
			url: "/pages/pay/index?order_id=" + goParam.order_id + "&type=" + goParam.order_type
		});
	} else if (goType == 'appointIndex') {
		if (common.checkIsFooterPage(goPath)) {
			wx.switchTab({
				url: goPath
			});
		} else {
			wx.navigateTo({
				url: goPath,
			})
		}
	} else if (goType == 'villageIndex') {
		if (common.checkIsFooterPage(goPath)) {
			wx.switchTab({
				url: goPath
			});
		} else {
			wx.navigateTo({
				url: goPath,
			})
		}
	} else if (goType == 'villageConvenient') {
		if (common.checkIsFooterPage(goPath)) {
			wx.switchTab({
				url: goPath
			});
		} else {
			wx.navigateTo({
				url: goPath
			})
		}
	} else if (goType == 'villageResident') {
		if (common.checkIsFooterPage(goPath)) {
			wx.switchTab({
				url: goPath
			});
		} else {
			wx.navigateTo({
				url: goPath
			})
		}
	} else if (goType == 'villageMyindex') {
		if (common.checkIsFooterPage(goPath)) {
			wx.switchTab({
				url: goPath
			});
		} else {
			wx.navigateTo({
				url: goPath
			})
		}
	} else if (goType == 'page') {
		console.log('goPath', goPath);
		wx.navigateTo({
			url: goPath
		})
	} else if (goType == 'url') {
		console.log('url', url);
		// #ifdef H5
		if (url.indexOf('url') == 0) {
			tmpArr = url.split('/');
			url = '/wap.php?c=' + tmpArr[1] + '&a=' + tmpArr[2];
			if (process.env.NODE_ENV === 'development') {
				// url = 'http://www.group.com' + url;
			}
			console.log('333333332222', url)
		}
		wx.hideLoading();
		if (common.$checkPlat.checkAlipayApp()) {
			url = '/pages/foodshop/index/index?webview_url=' + encodeURIComponent(url) + '&webview_title=' + encodeURIComponent(
				'打开新页面')
			if (!common.isAliApp) {
				loadJs("https://appx/web-view.min.js", function() {
					common.isAliApp = true
					my.navigateTo({
						url: url
					});
				});
			} else {
				my.navigateTo({
					url: url
				});
			}
		} else {
			var wxapp_config = wx.getStorageSync('wxapp_config');
			if (wxapp_config.city && wxapp_config.city.top_city && wxapp_config.city.top_city.area_id && url.indexOf('now_city=') ==
				-1) {
				url = common.changeURLArg(url, 'now_city', wxapp_config.city.top_city.area_id);
			}
			if (wxapp_config.city && wxapp_config.city.top_city && wxapp_config.city.area_id != wxapp_config.city.top_city.area_id &&
				url.indexOf('now_area=') == -1) {
				url = common.changeURLArg(url, 'now_area', wxapp_config.city.area_id);
			}
			var shop_city = app ? app.globalData.delivery_address : '';
			if (shop_city) {
				url = common.changeURLArg(url, 'now_shop_city', shop_city.city_id);
			}
			url = common.changeURLArg(url, 'wxappp_version', wxappVersionCode);
			if (wxapp_config.config && wxapp_config.config.open_multilingual && wxapp_config.config.open_multilingual == 1) {
				url = common.changeURLArg(url, 'now_lang', wxapp_config.config.lang_config.now_lang);
			}
			
			location.href = url
		}

		return
		// #endif

		// #ifdef MP-WEIXIN || MP-ALIPAY
		if (url.indexOf('wxapp') == 0) {
			var arr = url.split('://')
			console.log('跳转小程序参数', arr)
			wx.navigateToMiniProgram({
				appId: arr[1],
				path: arr[2] ? arr[2] : '',
				success(res) {
					console.log('打开小程序成功appId=' + arr[1])
				}
			})
			wx.hideLoading()
			return
		}

		var wxapp_config = wx.getStorageSync('wxapp_config');
		if (url.indexOf('url') == 0) {
			tmpArr = url.split('/');
			url = requestDomain + 'wap.php?c=' + tmpArr[1] + '&a=' + tmpArr[2];
		}
		url = url.replace('http://', 'https://');
		if (url.indexOf('https://') < 0 && url.indexOf('/') == 0) {
			url = requestDomain + url.substr(1);
		} else {
			tmpArr = url.split('/');
			var arr2 = requestDomain.split('/');
			var arr1 = wxapp_config.wxapp_domain_list ? wxapp_config.wxapp_domain_list : [];
			arr1.push(arr2[2], 'im-link.weihubao.com');
			console.log('能否打开网址', wxapp_config, arr1, tmpArr[2])
			arr1 = arr1.filter(item => item == tmpArr[2])
			if (arr1.length === 0) {
				wx.showModal({
					title: common.changeTxt('提示'),
					content: common.changeTxt('不支持打开该链接！'),
					showCancel: false
				})
				wx.hideLoading();
				return false;
			}
		}

		if (url.indexOf('Service&a=publish_detail&type=2') > 0) {
			if (wxapp_config && wxapp_config.config.wxapp_paotui_appid && wxapp_config.config.wxapp_paotui_appid != '') {
				wx.navigateToMiniProgram({
					appId: wxapp_config.config.wxapp_paotui_appid,
					success: function() {

					},
					fail: function(res) {
						common.parseUrl(url.replace('Service&a=publish_detail&type=2', 'Service&a=index&new_service=1'), '', false,
							pageTitle);
					}
				});
				wx.hideLoading()
				return false;
			}
		}
		if (!pageTitle) {
			pageTitle = "";
		}
		url = common.changeURLArg(url, 'device_id', common.device_id);

		var ticket = uni.getStorageSync('ticket');
		if (ticket) {
			url = common.changeURLArg(url, 'ticket', ticket);
		}
		if (wxapp_config.city && wxapp_config.city.top_city && wxapp_config.city.top_city.area_id && url.indexOf('now_city=') ==
			-1) {
			url = common.changeURLArg(url, 'now_city', wxapp_config.city.top_city.area_id);
		}
		if (wxapp_config.city && wxapp_config.city.top_city && wxapp_config.city.area_id != wxapp_config.city.top_city.area_id &&
			url.indexOf('now_area=') == -1) {
			url = common.changeURLArg(url, 'now_area', wxapp_config.city.area_id);
		}
		var shop_city = app ? app.globalData.delivery_address : '';
		if (shop_city) {
			url = common.changeURLArg(url, 'now_shop_city', shop_city.city_id);
		}
		url = common.changeURLArg(url, 'wxappp_version', wxappVersionCode);
		if (wxapp_config.config && wxapp_config.config.open_multilingual && wxapp_config.config.open_multilingual == 1) {
			url = common.changeURLArg(url, 'now_lang', wxapp_config.config.lang_config.now_lang);
		}

		console.log('打开的webview页面链接', url);
		uni.navigateTo({
			url: "/pages/webview/webview?webview_url=" + encodeURIComponent(url) + "&webview_title=" + encodeURIComponent(
				pageTitle)
		});
		// #endif
	}

	wx.hideLoading()

}

common.gotoShopPage = function(goType, goParam, pageTitle) {
	if (goType == 'shopIndex') {
		console.log('快店跳转')
		if (common.checkIsFooterPage("/pages/shop_index/index")) {
			uni.switchTab({
				url: "/pages/shop_index/index"
			});
		} else {
			uni.navigateTo({
				url: '/pages/nofooter/shop/shop_index',
			})
		}
	} else if (goType == 'shopDetail') {
		// #ifdef H5
		if (common.$checkPlat.checkWeixinApp()) {
			common.jweixin.miniProgram.navigateTo({
				url: "/pages/shop_new/shopDetail/shopDetail?store_id=" + goParam
			});
		} else {
			uni.navigateTo({
				url: "/pages/shop_new/shopDetail/shopDetail?store_id=" + goParam
			});
		}
		// #endif

		// #ifdef MP-WEIXIN || MP-ALIPAY
		uni.navigateTo({
			url: "/pages/shop_new/shopDetail/shopDetail?store_id=" + goParam
		});
		// #endif

	} else if (goType == 'shopCat') {
		uni.navigateTo({
			url: "/pages/shop_new/shopType/shopType?cat_url=" + goParam + (pageTitle ? "&title=" + encodeURIComponent(
				pageTitle) : '')
		});
	} else if (goType == 'shopGood') {
		if (goParam.length == 2) {
			uni.navigateTo({
				url: '/pages/shop_new/goodsDetail/goodsDetail?product_id=' + goParam[0] + '&store_id=' + goParam[1],
			})
		}
	}
	wx.hideLoading()
}

common.checkIsFooterPage = function(path) {
	console.log('checkIsFooterPage', app.globalData.tabBar.list);
	var is_footer = false
	for (var i = 0; i < app.globalData.tabBar.list.length; i++) {
		if (app.globalData.tabBar.list[i].pagePath == path) {
			is_footer = true
			break
		}
	}
	return is_footer
}

common.changeURLArg = function(url, arg, arg_val) {
	if (url.match('vote_app') || url.match('pages/vote')) {
		var replaceText = arg + '=' + arg_val;
		if (url.match('[\?]')) {
			new_url = url + '&' + replaceText;
		} else {
			new_url = url + '?' + replaceText;
		}
		return new_url;
	}
	var urlArr = url.indexOf('#/pages/') > 0 ? [url] : url.split('#'); // uni页面不处理
	url = urlArr[0];
	var pattern = arg + '=([^&]*)';
	var replaceText = arg + '=' + arg_val;
	var new_url = '';
	if (url.match(pattern)) {
		var tmp = '/(' + arg + '=)([^&]*)/gi';
		console.log('tmp', tmp);
		new_url = url.replace(tmp, replaceText);
	} else {
		if (url.match('[\?]')) {
			new_url = url + '&' + replaceText;
		} else {
			new_url = url + '?' + replaceText;
		}
	}
	return urlArr.length >= 2 ? new_url + '#' + urlArr[1] : new_url;
}

var urlParamObj = {};
common.getUrlParam = function(url, paramName) {

	if (!urlParamObj[url]) {
		var param = url.substr(url.indexOf('?') + 1);
		var arr = param.split("&");
		console.log('arr', arr);
		urlParamObj[url] = {}
		for (var i = 0; i < arr.length; i++) {
			var paramArr = arr[i].split("=");
			urlParamObj[url][paramArr[0]] = paramArr[1];
		}
	}
	if (urlParamObj[url][paramName]) {
		return urlParamObj[url][paramName];
	} else {
		return '';
	}

}
/***
 * wxAutoImageCal 计算宽高
 * 
 * 参数 e: iamge load函数的取得的值
 * 返回计算后的图片宽高
 * {
 *  imageWidth: 100px;
 *  imageHeight: 100px;
 * }
 */
common.wxAutoImageCal = function(e) {
	console.dir(e);
	//获取图片的原始长宽
	var originalWidth = e.detail.width;
	var originalHeight = e.detail.height;
	var windowWidth = 0,
		windowHeight = 0;
	var autoWidth = 0,
		autoHeight = 0;
	var results = {};
	wx.getSystemInfo({
		success: function(res) {
			console.dir(res);
			windowWidth = res.windowWidth;
			windowHeight = res.windowHeight;
			//判断按照那种方式进行缩放
			console.log("windowWidth" + windowWidth);
			if (originalWidth > windowWidth) { //在图片width大于手机屏幕width时候
				autoWidth = windowWidth;
				console.log("autoWidth" + autoWidth);
				autoHeight = (autoWidth * originalHeight) / originalWidth;
				console.log("autoHeight" + autoHeight);
				results.imageWidth = autoWidth;
				results.imageheight = autoHeight;
			} else { //否则展示原来的数据
				results.imageWidth = originalWidth;
				results.imageheight = originalHeight;
			}
		}
	})

	return results;

}


common.floatVal = function(numVal) {
	if (typeof(numVal) == 'string') {
		numVal = Number(numVal);
	}
	var str = numVal.toFixed(2);
	if (str.indexOf('.') >= 0) {
		if (str.substr(-3) == '.00') {
			return numVal.toFixed(0);
		} else if (str.substr(-1) == '0') {
			console.log(str);
			return numVal.toFixed(1);
		}
	}
	return str;
}
common.copyText = function(text) {
	wx.setClipboardData({
		data: text,
		success: function(res) {
			wx.showToast({
				title: common.changeTxt('复制成功'),
				icon: 'success',
				duration: 2000
			})
		},
	});
}


common.ab2hext = function(buffer) {
	var hexArr = Array.prototype.map.call(
		new Uint8Array(buffer),
		function(bit) {
			return ('00' + bit.toString(16)).slice(-2)
		}
	)
	return hexArr.join('');
}

common.parseGoodBarcode = function(barcode) {
	common.post('Shop_new&a=barcodeGetName', {
		barcode: barcode
	}, (data) => {
		wx.navigateTo({
			url: '/pages/shop_new/search/search?type=barcode&key=' + barcode + '&name=' + encodeURIComponent(data.name),
			complete() {
				wx.hideLoading();
			}
		});
	});
}

// 判断字符串是否以xxx结尾
common.strEndWith = function(str, endStr) {
	var d = str.length - endStr.length;
	return (d >= 0 && str.lastIndexOf(endStr) == d)
}


//格式化时间
common.formatTime = function(date) { 
	if (!date) {
		date = new Date();
	}
	var year = date.getFullYear()
	var month = date.getMonth() + 1
	var day = date.getDate()

	var hour = date.getHours()
	var minute = date.getMinutes()
	var second = date.getSeconds()


	return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

function formatNumber(n) {
	n = n.toString()
	return n[1] ? n : '0' + n
}

common.getWxconfig = function(callback) {
	let _url = window.location.href
	console.log('请求wx.config开始', common.jweixin)
	common.post('Config&a=wx_config', {
		noTip: true,
		work: 'community_group',
		location_url: _url
	}, function(_lists) {
		console.log('请求wx.config成功', _lists)
		// 注入配置
		common.jweixin.config({
			debug: false,
			appId: _lists.appId,
			timestamp: _lists.timestamp,
			nonceStr: _lists.nonceStr,
			signature: _lists.signature,
			jsApiList: ['checkJsApi', 'onMenuShareTimeline', 'onMenuShareAppMessage', 'onMenuShareQQ', 'onMenuShareWeibo',
				'scanQRCode', 'previewImage', 'openLocation', 'getLocation', 'getNetworkType', 'updateAppMessageShareData',
				'updateTimelineShareData'
			]
		}, (e) => {
			console.log('请求wx.config报错', e)
		})

		common.jweixin.ready(function() {
			common.jweixin.checkJsApi({
				jsApiList: ['checkJsApi', 'onMenuShareTimeline', 'onMenuShareAppMessage', 'onMenuShareQQ',
					'onMenuShareWeibo', 'scanQRCode', 'previewImage', 'openLocation', 'getLocation', 'getNetworkType'
				],
				success: function(res) {
					console.log('微信配置成功')
					if (callback) {
						callback()
					}
				}
			})
		})
	})
}
common.wxHideShare = function() {
	common.jweixin.ready(function() {
		common.jweixin.hideOptionMenu();
	})
}

common.wxShare = function() {
	let share = JSON.parse(JSON.stringify(shareWxData))
	if (JSON.stringify(share) == '{}') {
		return
	}
	shareWxData = {}
	let defaultUrl = window.location.href
	if (share.sendFriendLink) {
		defaultUrl = share.sendFriendLink
	}
	common.jweixin.ready(function() {
		common.jweixin.showOptionMenu();
		common.jweixin.onMenuShareAppMessage({
			title: share.title,
			desc: share.desc,
			link: defaultUrl,
			imgUrl: share.share_img,
			success: function() {
				uni.showToast({
					title: common.changeTxt('分享成功')
				})
			}
		})
		common.jweixin.onMenuShareTimeline({
			title: share.title,
			link: defaultUrl,
			imgUrl: share.share_img,
			success: function() {
				uni.showToast({
					title: common.changeTxt('分享成功')
				})
			}
		})
		common.jweixin.onMenuShareWeibo({
			title: share.title,
			desc: share.desc,
			link: defaultUrl,
			imgUrl: share.share_img,
			success: function() {
				uni.showToast({
					title: common.changeTxt('分享成功')
				})
			}
		})
		common.jweixin.updateAppMessageShareData({
			title: share.title, // 分享标题
			desc: share.desc, // 分享描述
			link: defaultUrl, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
			imgUrl: share.share_img // 分享图标
		})
		common.jweixin.updateTimelineShareData({
			title: share.title, // 分享标题
			link: defaultUrl, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
			imgUrl: share.share_img // 分享图标
		})
	})
}
common.hideWxShare = function() {
	if (common.$checkPlat.checkWeixin()) {
		if (common.$checkPlat.checkAndroid()) {
			common.getWxconfig(common.wxHideShare)
		} else {
			common.wxHideShare()
		}
	}
}
var shareWxData = {}
common.setWxShare = function(shareData) {
	if (common.$checkPlat.checkWeixin()) {
		shareWxData = shareData
		if (common.$checkPlat.checkAndroid()) {
			common.getWxconfig(common.wxShare)
		} else {
			common.wxShare()
		}
	}
}

common.navigateBack = function(delta) {
	if (!delta) {
		delta = 1
	}
	// #ifdef MP-WEIXIN || MP-ALIPAY
	uni.navigateBack({
		delta: delta
	});
	// #endif

	// #ifdef H5
	var pages = getCurrentPages()
	if (pages.length > 1) {
		uni.navigateBack({
			delta: delta
		});
	} else {
		history.go(-delta)
	}
	// #endif
}

function loadJs(url, callback) {
	var script = document.createElement('script');
	script.type = "text/javascript";
	if (typeof(callback) != "undefined") {
		if (script.readyState) {
			script.onreadystatechange = function() {
				if (script.readyState == "loaded" || script.readyState == "complete") {
					script.onreadystatechange = null;
					callback();
				}
			}
		} else {
			script.onload = function() {
				callback();
			}
		}
	}
	script.src = url;
	document.body.appendChild(script);
}

// js代码中的文字替换
common.getTxtKey = function(keywords, param) {
	if (keywords == '') {
		return ''
	}
	if (!app) {
		app = getApp();
	}
	if (!param) {
		param = {}
	}
	console.log('33333', app);
	return new Promise((resolve, reject) => {
		common.getConfig(function(data) {
			if (data.config.open_multilingual != 1 || (data.config.open_multilingual == 1 && data.config.lang_config.now_lang ==
					'chinese')) {
				keywords = common.stitchKey(keywords, param)
				resolve(keywords)
			} else {
				common.getLangData(function(langData) {
					if (typeof langData[keywords] == 'undefined') {
						common.reportLanguage(keywords);
						app.globalData.languageData[keywords] = keywords;
						keywords = common.stitchKey(keywords, param)
						console.log('111', keywords)
					} else if (langData[keywords] == '') {
						keywords = common.stitchKey(keywords, param)
						console.log('222', keywords)
					} else {
						keywords = common.stitchKey(langData[keywords], param)
						console.log('333', keywords)
					}
					resolve(keywords)
				})
			}
		})
	});
}
common.changeTxt = function(keywords, param) {
	if (!app) {
		app = getApp();
	}
	if (keywords == '') {
		return '';
	}

	if (!param) {
		param = {};
	}

	if (!app.globalData.open_multilingual) {
		keywords = common.stitchKey(keywords, param);
	} else {
		if (app.globalData.languageData !== null) {
			if (app.globalData.languageData[keywords] == undefined) {
				app.globalData.languageData[keywords] = keywords;

				common.reportLanguage(keywords);

				keywords = common.stitchKey(keywords, param);
			} else if (app.globalData.languageData[keywords] == '') {
				keywords = common.stitchKey(keywords, param);
			} else {
				keywords = common.stitchKey(app.globalData.languageData[keywords], param);
			}
		} else {
			keywords = common.stitchKey(keywords, param);
		}
	}

	return keywords;
}

// 拼接字符串
common.stitchKey = function(key, param) {

	if (!app) {
		app = getApp();
	}
	try {
		if (param.unit1) {
			if (!app.globalData.open_multilingual || !app.globalData.config.config.lang_config || app.globalData.config
				.config.lang_config.now_lang == 'chinese') {
				param.X1 += param.unit1;
			} else {
				param.X1 += ' ' + param.unit1;
			}
		}

		if (param.unit2) {
			if (!app.globalData.open_multilingual || !app.globalData.config.config.lang_config || app.globalData.config
				.config.lang_config.now_lang == 'chinese') {
				param.X2 += param.unit2;
			} else {
				param.X2 += ' ' + param.unit2;
			}
		}

		if (key.indexOf('X1') != -1) {
			key = key.replace(/X1/, param.X1);
		}

		if (key.indexOf('X2') != -1) {
			key = key.replace(/X2/, param.X2);
		}

		if (!app.globalData.open_multilingual || !app.globalData.config.config.lang_config || app.globalData.config.config
			.lang_config.now_lang == 'chinese') {
			if (param.left) {
				param.left = false;
			}

			if (param.right) {
				param.right == false;
			}
		}

		if (param.left) {
			key = ' ' + key;
		}

		if (param.right) {
			key = key + ' ';
		}

		return key;
	} catch (e) {
		console.log('多语言转化时候的错误', e);
		return key;
	}
}

// 上报语言缺少值
common.reportLanguage = function(keywords) {
	if (!app) {
		app = getApp()
		common.reportLanguage(keywords)
		return
	}
	common.post('Lang&a=report', {
		keywords: keywords,
		from: 'wxapp',
		noTip: true
	}, data => {
		if (data[0]) {
			app.globalData.languageData[keywords] = data[0].key;
		}
	});
}

//设置页面颜色
// param page  页面的 this
// param callbackFun  回调方法
// param changeColor 是否更换颜色，可能只调用获取一下 config值， 全等于 false 才是不换，不传或 true 是换
common.setMainColor = function(page, callbackFun, changeColor) {
	if (!app) {
		app = getApp()
		common.setMainColor(page, callbackFun)
		return
	}
	console.log('要换颜色了.....', (page.__route__ ? page.__route__ : page.route));
	var time = setInterval(() => {
		if (app.globalData.config) {
			clearInterval(time);
			console.log('changeColor', changeColor);
			if(changeColor !== false){
				uni.setNavigationBarColor({
					frontColor: '#ffffff',
					backgroundColor: app.globalData.config.config.mobile_head_color,
					success: function(successRes) {
						console.log((page.__route__ ? page.__route__ : page.route) + '换颜色成功了', successRes);
					},
					fail: function(failRes) {
						console.log((page.__route__ ? page.__route__ : page.route) + '换颜色失败了', failRes);
					}
				});
			}
			page.config = app.globalData.config
			page.mobile_head_color = app.globalData.config.config.mobile_head_color
			typeof callbackFun == "function" && callbackFun(app.globalData.config);
		}
	}, 100);
}

// 清空自定义底部导航的tabBar缓存
common.clearTabbarBusiness = function(type){
	app.globalData.tabbarBusiness[type] = null;
}

// 自定义底部tabBar,子业务重载用的
common.editTabbarBusiness = function(param, callFun){
	if (!app) {
		app = getApp()
		common.editTabbarBusiness(param, callFun)
		return
	}
	if (!param) {
		param = {};
	}
	if (!param.type) {
		param.type = 'village';
	}
	if(!param.postParam){
		param.postParam = {};
	}
	if(param.type == 'village'){
		var tabbarGetUrl = 'House_index&a=footer_list';
	}
	
	if (app.globalData.tabbarBusiness[param.type]) {
		var tabbar = app.globalData.tabbarBusiness[param.type];
		console.log('tabbar', tabbar);
		callFun(tabbar)
	}else{
		common.post(tabbarGetUrl, param.postParam, function(result){
			app.globalData.tabbarBusiness[param.type] = result;
			callFun(result)
		});
	}
}

// 自定义底部tabBar
common.editTabbar = function(param, callFun) {
	if (!app) {
		app = getApp()
		common.editTabbar(param, callFun)
		return
	}
	uni.hideTabBar();

	if (!param) {
		param = {};
	}

	var time = setInterval(() => {
		if ((app.globalData.languageData != null || app.globalData.config !== null && app.globalData.config.config &&
				app.globalData.config.config.open_multilingual != 1) && app.globalData.tabBar != null) {

			let tabbar = app.globalData.tabBar;
			let currentPages = getCurrentPages();
			let _this = currentPages[currentPages.length - 1];
			console.log('currentPages', currentPages);
			console.log('currentPages_page', _this);
			let pagePath = _this.route ? _this.route : _this.__proto__.route;
			if (!pagePath) {
				return;
			}

			clearInterval(time);

			console.log('editTabbar', _this, pagePath)
			pagePath.indexOf('/') != 0 && (pagePath = '/' + pagePath); // 判断当前页面是否是首页

			if (pagePath == '/') {
				pagePath = firstPage
			}

			if (firstOpen && tabbar.list[0].pagePath != firstPage && pagePath == firstPage) {
				firstOpen = false;
				clearInterval(_this.timer);
				console.log('999999999999999999999999999911', tabbar)
				if (tabbar.list[0].pagePath.indexOf('/pages/') === 0) {
					wx.reLaunch({
						url: tabbar.list[0].pagePath
					});
				} else {
					if (tabbar.list.length > 1) {
						common.parseUrl(tabbar.list[0].pagePath);
					} else {
						tabbar.hidden = true;
						app.globalData.tabWeb = {
							url: tabbar.list[0].pagePath,
							title: tabbar.list[0].text
						};
						wx.reLaunch({
							url: '/pages/webview/tab_webview'
						});
					}
				}
			}

			for (let i in tabbar.list) {
				tabbar.list[i].selected = false;
				tabbar.list[i].pagePath == pagePath && (tabbar.list[i].selected = true);
			}
			_this.tabbar = {}
			_this.tabbar.hidden = false
			if (param.hidden) {
				tabbar.hidden = true;
			} else {
				tabbar.hidden = false;
			}
			tabbar.tabbar_type = 'tabbar';
			console.log('tabbar.hidden', tabbar.hidden);
			_this.tabbar = tabbar;

			//#ifdef MP-ALIPAY || MP-WEIXIN
			(typeof callFun == 'function') && callFun(tabbar)
			//#endif

		}
	}, 100);
}

common.setUserInfo = function(result) {
	if (!app) {
		app = getApp()
		common.setUserInfo(result)
		return
	}
	if (result.emptyUser) {
		uni.removeStorageSync('ticket');
		common.getUserInfo(callbackObj);
	} else {
		uni.setStorageSync('ticket', result.ticket);
		uni.setStorageSync('openId', result.user.openid);

		if (result.user.phone) {
			uni.setStorageSync('isPlatUser', '1');
		} else {
			uni.setStorageSync('isPlatUser', '0');
			result.user.phone = '';
		}

		app.globalData.userInfo = result.user;
		uni.setStorageSync('auto_door_open', result.user.auto_door_open);
		typeof callbackObj == "function" && callbackObj(app.globalData.userInfo);
	}
}

common.getUserInfo = function(cb, failcb) {
	if (!app) {
		app = getApp()
		common.getUserInfo(cb, failcb)
		return
	}

	var _this = common;

	if (app.globalData.userInfo) {
		typeof cb == "function" && cb(app.globalData.userInfo);
	} else {
		console.log('1111111111111111111')
		//调用登录接口
		var ticket = uni.getStorageSync('ticket');

		if (ticket) {
			callbackObj = cb;
			let url = 'Wxapp&a=login'
			// #ifdef H5
			url = 'Login&a=login'
			// #endif
			common.post(url, {
				ticket: ticket
			}, "setUserInfo", _this);
		} else {
			uni.login({
				success: function(result) {
					console.log(result);
					wx.setStorageSync('code', result.code);
					uni.getUserInfo({
						lang: 'zh_CN',
						success: function(res) {
							callbackObj = cb;
							common.post('Wxapp&a=login', {
								code: result.code,
								encryptedData: res.encryptedData,
								iv: res.iv
							}, "setUserInfo", _this);
						},
						fail: function(result) {
							console.log(result);

							if (result.errMsg.indexOf("fail scope unauthorized") != -1) {
								console.log(_this);

								if (typeof failcb == "function") {
									failcb('fail scope unauthorized');
								} else {
									/*wx.navigateTo({ url: "/pages/index/authorize" });*/
								}

								return false;
							}

							if (typeof failcb == "function") {
								failcb(result.errMsg);
							} else if (failcb == 'back') {
								wx.showModal({
									title: common.changeTxt('提示'),
									content: common.changeTxt('微信登录失败，将自动回到上一个页面'),
									showCancel: false,
									success: function(res) {
										if (res.confirm) {
											wx.navigateBack();
										}
									}
								});
							} else if (failcb == 'need') {
								wx.showModal({
									title: common.changeTxt('提示'),
									content: common.changeTxt('微信登录失败，该页面必须要微信登录。将重新使用微信登录'),
									showCancel: false,
									success: function(res) {
										if (res.confirm) {
											_this.getUserInfo(cb);
										}
									}
								});
							} else if (failcb == 'setting') {
								wx.openSetting({
									success: function(res) {
										if (res.authSetting['scope.userInfo'] == false) {
											wx.showModal({
												title: common.changeTxt('提示'),
												content: common.changeTxt('微信登录失败，将自动回到上一个页面'),
												showCancel: false,
												success: function(res) {
													if (res.confirm) {
														wx.navigateBack();
													}
												}
											});
										} else {
											_this.getUserInfo(cb);
										}
									}
								});
							}
						}
					});
				},
				fail: function(res) {
					console.log('wx-login-error', res);
				}
			});
		}
	}
}

// 有ticket无用户信息的情况下
common.getUser = function(callFun) {
	if (!app) {
		app = getApp()
		common.getUser(callFun)
		return
	}
	setTimeout(function() {
		if (app.globalData.userInfo) {
			callFun()
		} else {
			common.getUser(callFun)
		}
	}, 200)
}

// uni框架下 h5跳转到对应原生页面
common.webToMiniapp = function(path, options, goOrRedirect) {
	if (!app) {
		app = getApp()
		common.webToMiniapp(path, options, goOrRedirect)
		return
	}
	if (path.substr(0, 1) != '/') {
		path = '/' + path;
	}
	if (app.globalData.isAliapp || app.globalData.isWxapp) {
		let url = path
		let str = ''
		for (let i in options) {
			str = str + i + '=' + options[i] + '&'
		}
		str = str.slice(0, -1)
		url = url + '?' + str
		console.log('uni框架下 h5跳转到对应原生页面', url)
		if (app.globalData.isAliapp) {
			if (goOrRedirect == 'redirect') {
				my.redirectTo({
					url: url
				})
			} else {
				my.navigateTo({
					url: url
				})
			}
		} else if (app.globalData.isWxapp) {
			if (goOrRedirect == 'redirect') {
				common.jweixin.miniProgram.redirectTo({
					url: url
				})
			} else {
				common.jweixin.miniProgram.navigateTo({
					url: url
				})
			}
		}
		return
	}
}

// 页面获取config的方法
common.getConfig = (callFun) => {
	if (app && app.globalData.config) {
		callFun(app.globalData.config)
	} else {
		setTimeout(function() {
			common.getConfig(callFun)
		}, 300)
	}
}

common.getTabBar = (callFun) => {
	console.log("获取底部导航", app.globalData.tabBar)
	if (!app) {
		app = getApp()
		common.getTabBar(callFun)
		return
	}
	if (app && app.globalData.tabBar) {
		callFun(app.globalData.tabBar)
	} else {
		setTimeout(function() {
			common.getTabBar(callFun)
		}, 300)
	}
}

common.location_report = function(lng, lat, type) {
	if (!app) {
		app = getApp()
		common.location_report(lng, lat, type)
		return
	}
	if (app.globalData.userInfo) {
		setTimeout(function() {
			common.post('Userlonglat&a=report', {
				lng: lng,
				lat: lat,
				type: type,
				noTip: true
			}, function() {}, app);
		}, 300);
	}
}

common.log_report = function(msg, file) {
	var systemInfo = wx.getSystemInfoSync();
	common.post('Config&a=wxapp_door_report', {
		msg: msg,
		systemInfo: systemInfo,
		file: file,
		noTip: true
	}, function() {}, this);
}

// 货币符号显示
common.changeCurrency = (page) => {
	common.getConfig(function(data) {
		page.currency = data.config.Currency_symbol
	})
}

// 兼容微信SDK环境的统一定位方法
var wxLocationParam = {}
common.locationFun = (callFun, that, ltype, geoType) => {
	// geoType 可以设置为wgs84  gcj02

	// #ifdef H5
	if (common.$checkPlat.checkWeixin()) {
		wxLocationParam = {
			callFun,
			that,
			ltype
		}
		if (common.$checkPlat.checkAndroid()) {
			console.log('使用微信定位1')
			common.getWxconfig(common.locationByWx)
		} else {
			// 微信浏览器定位
			console.log('使用微信定位2')
			common.locationByWx()
		}
	} else {
		common.getLocation(callFun, that, ltype, 0, 0, geoType)
	}
	// #endif

	// #ifdef MP-ALIPAY || MP-WEIXIN
	common.getLocation(callFun, that, ltype)
	// #endif
}

// 微信SDK定位
common.locationByWx = () => {
	if (!wxLocationParam.callFun) {
		return
	}
	console.log('使用微信定位333')
	let options = {
		lng: '',
		lat: '',
		errorMsg: ''
	}
	let callFun = wxLocationParam.callFun
	let that = wxLocationParam.that
	let ltype = wxLocationParam.ltype
	let geoType = wxLocationParam.geoType
	wxLocationParam = {}

	common.jweixin.error(function(res) {
		if (typeof res == 'object' && res.errMsg) {
			// uni.showToast({
			// 	title: common.changeTxt('微信接口报错' + res.errMsg),
			// 	icon: 'none'
			// })
			console.log('微信接口报错', res.errMsg)
		}
	})
	common.jweixin.ready(function() {
		common.jweixin.getLocation({
			type: 'wgs84',
			success: function(res) {
				var lng = res.longitude
				var lat = res.latitude
				console.log('微信定位成功', res, options)
				if (ltype == 'baidu') {
					console.log('将定位信息转换成百度定位信息')
					common.changeLocation(callFun, that, lng, lat, ltype)
				} else {
					callFun({
						lng,
						lat
					})
				}
			},
			fail: function(res) {
				callFun(res)
			},
			cancel: function(res) {
				callFun(res)
			}
		})
	})
}

// 获取语言包
common.getLangData = (callFun) => {
	if (app && app.globalData.languageData) {
		callFun(app.globalData.languageData)
	} else {
		setTimeout(function() {
			common.getLangData(callFun)
		}, 300)
	}
}

// 给分享链接添加推广人参数 spread_uid
common.addShareParam = (url) => {
	if (!app) {
		app = getApp()
	}
	if (!app.globalData.is_login) {
		return url
	}

	let spread_uid = app.globalData.userInfo.uid
	
	url = common.changeURLArg(url, 'spread_uid', spread_uid);

	console.log('share url', url)
	return url
}

// 告知后台当前用户的推广人
common.reportSpread = (spread_uid) => {
	if (!app) {
		app = getApp()
	}
	
	common.post('Spread&a=spread', {
		spread_uid: spread_uid,
		noTip: true
	}, (data) => {
		console.log('推广上报成功', data)
	}, '', (err) => {
		console.log('推广上报错误', err)
	})
}

// 后台返回的数据数组进行按字段值进行去重
common.unique_arr = (arr, key) => {
	return Array.from(new Set(arr.map(e => e[key]))).map(e => arr.find(x => x[key] == e));
}

module.exports = common
